<?php

/**
 * This is the model class for table "{{tag}}".
 *
 * The followings are the available columns in table '{{tag}}':
 * @property integer $tag_id
 * @property string $tag_name
 * @property integer $tag_frequency
 * @property integer $created
 * @property integer $modified
 */
class Tag extends CActiveRecord {
    /**
     * Returns the static model of the specified AR class.
     * @return Tag the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{tag}}';
    }

    /**
     * add default created modified time
     */

    public function behaviors() {
        return array(
                'AutoTimestampBehavior' => array(
                        'class' => 'application.components.AutoTimestampBehavior',
                //You can optionally set the field name options here
                )
        );
    }
    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
                array('tag_name', 'required'),
                array('tag_frequency', 'numerical', 'integerOnly'=>true),
                array('tag_name', 'length', 'max'=>128),
                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('tag_id, tag_name, tag_frequency, created, modified', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * add default desc
     */

    public function scopes() {
        return array(
                'published'=>array(
                        'order'=>'created desc',
                ),
        );

    }
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
                'tag_id' => 'Tag',
                'tag_name' => 'Tag Name',
                'tag_frequency' => 'Tag Frequency',
                'created' => 'Created',
                'modified' => 'Modified',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('tag_id',$this->tag_id);
        $criteria->compare('tag_name',$this->tag_name,true);
        $criteria->compare('tag_frequency',$this->tag_frequency);
        $criteria->compare('created',$this->created);
        $criteria->compare('modified',$this->modified);

        return new CActiveDataProvider(get_class($this), array(
                        'criteria'=>$criteria,
        ));
    }

    public function getLink() {
        return CHtml::link(CHtml::encode($this->tag_name), array('index/index', 'tag'=>$this->tag_name));
    }

    public static function string2array($tags) {
        return preg_split('/\s*,\s*/',trim($tags),-1,PREG_SPLIT_NO_EMPTY);
    }

    public static function array2string($tags) {
        return implode(', ',$tags);
    }

    public function updateFrequency($oldTags, $newTags) {
        $oldTags=self::string2array($oldTags);
        $newTags=self::string2array($newTags);
        $this->addTags(array_values(array_diff($newTags,$oldTags)));
        $this->removeTags(array_values(array_diff($oldTags,$newTags)));
    }

    public function addTags($tags) {
        $criteria=new CDbCriteria;
        $criteria->addInCondition('tag_name',$tags);
        $this->updateCounters(array('tag_frequency'=>1),$criteria);
        foreach($tags as $name) {
            if(!$this->exists('tag_name=:name',array(':name'=>$name))) {
                $tag=new Tag;
                $tag->tag_name=$name;
                $tag->tag_frequency=1;
                $tag->save();
            }
        }
    }

    public function removeTags($tags) {
        if(empty($tags))
            return;
        $criteria=new CDbCriteria;
        $criteria->addInCondition('tag_name',$tags);
        $this->updateCounters(array('tag_frequency'=>-1),$criteria);
        $this->deleteAll('tag_frequency<=0');
    }
}